package com.controller;

import com.po.Comment;
import com.po.User;
import com.service.ActivityService;
import com.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private ActivityService activityService;

    @GetMapping("/comments/{id}")
    public String comments(@PathVariable Long id, Model model) {
        System.out.println("222");
        model.addAttribute("comments", commentService.listCommentByActivityId(id));
        System.out.println(model.getAttribute("comments"));
        return "activities :: commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session) {
        Long id = comment.getActivity().getId();
        comment.setActivity(activityService.getActivity(id));
        User user = (User) session.getAttribute("user");
        if (user.getId().equals(activityService.getActivity(id).getLead().getUser().getId())) {
            comment.setAdminComment(true);
        }else{
            comment.setAdminComment(false);
        }
        comment.setUser(user);
        commentService.saveComment(comment);
        return "redirect:/activities/" + id;
    }
}
